package com.qf.driver.service.impl;

import com.alibaba.fastjson.JSON;
import com.qf.common.bean.R;
import com.qf.common.dto.DeviceTopicDto;
import com.qf.common.model.QfDeviceTopic;
import com.qf.driver.feign.DeviceTopicFeign;
import com.qf.driver.mqtt.bean.MqttProperties;
import com.qf.driver.service.DeviceTopicService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 千锋健哥
 */
@Service
@Slf4j
public class DeviceTopicServiceImpl implements DeviceTopicService, BeanFactoryAware {

    @Autowired
    private DeviceTopicFeign deviceTopicFeign;

    @Autowired
    private MqttProperties mqttProperties;

    //声明spring中的Beanfactory属性
    private BeanFactory beanFactory;

    //从spring中的BeanFactoryAware接口中获取到Beanfactory对象给, 这里全局的Beanfactory属性赋值
    @Override
    public void setBeanFactory(BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    @Override
    public List<QfDeviceTopic> findAll() {
        R<List> result = deviceTopicFeign.findAll(new DeviceTopicDto());
        if (result  != null) {
            String jsonStr = JSON.toJSONString(result.getData());
            List<QfDeviceTopic> list = JSON.parseArray(jsonStr, QfDeviceTopic.class);
            return list;
        }
        return null;
    }

    @Override
    public void joinDeviceTopic(String deviceKey) {
        //1. 根据设备key查询对应的topic主题集合对象
        DeviceTopicDto dto = new DeviceTopicDto();
        dto.setDeviceKey(deviceKey);
        R<List> result = deviceTopicFeign.findAll(dto);
        if (result == null || result.getData() == null || result.getData().size() == 0 ) {
            log.info("======deviceKey=== "+ deviceKey + "===因设备topic无法找到, 所以无法连接======");
            return;
        }
        String jsonStr = JSON.toJSONString(result.getData());
        List<QfDeviceTopic> topicList = JSON.parseArray(jsonStr, QfDeviceTopic.class);

        //2. 获取mqttConfig初始化类中的emqx服务器订阅对象, 此对象无法注入需要spring中的BeanFactory对象加载
        Object mqttInbound = beanFactory.getBean("mqttInbound");
        MqttPahoMessageDrivenChannelAdapter mqttIn = (MqttPahoMessageDrivenChannelAdapter) mqttInbound;

        //3. 遍历topic列表
        if (topicList != null) {
            for (QfDeviceTopic qfDeviceTopic : topicList) {
                try {
                    //4. 加载topic主题到emqx服务器
                    mqttIn.addTopic(qfDeviceTopic.getTopic(), mqttProperties.getQos());
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("qfDeviceTopic:" + qfDeviceTopic + "===增量加载topic到emqx服务器异常");
                }
            }
        }

    }

}
